//
//  SYHomeParLeaveViewController.m
//  ChatDemo-UI2.0
//
//  Created by zz on 16/8/16.
//  Copyright © 2016年 zz. All rights reserved.
//

#import "SYHomeParLeaveViewController.h"
#import "SYLeaveSelView.h"
#import "DateView.h"
#import "XHMessageTextView.h"
#import "DropDownMenu2.h"

@interface SYHomeParLeaveViewController ()<SYLeaveSelViewDelegate,UITextViewDelegate,UIPickerViewDelegate,UIPickerViewDataSource,UITextFieldDelegate>

@property(nonatomic,strong) SYLeaveSelView *selClass; //选择班级
@property(nonatomic,strong) SYLeaveSelView *selType; //选择请假类型
@property(nonatomic,strong) SYLeaveSelView *selStartDate; //选择开始时间
@property(nonatomic,strong) SYLeaveSelView *selEndDate; //选择结束时间
@property(nonatomic,strong) SYLeaveSelView *selDays; //天数

@property(nonatomic,strong) DateView *dateViewStart;//开始时间
@property(nonatomic,strong) DateView *dateViewStop;//结束时间

@property(nonatomic,strong) XHMessageTextView *inputView;
@property(nonatomic,strong) UIView *contentView;
@property(nonatomic,strong) UILabel *countLabel; //统计textView输入的文字数

@property (nonatomic,strong) UITapGestureRecognizer *keyBoardHideTap;

@property (nonatomic,strong) UIPickerView *picker;//请假类型
@property (nonatomic,strong) UIPickerView *classPicker;//选择孩子班级
@property (nonatomic,assign) NSInteger indexOfType;//当前默认选中的请假类型
@property (nonatomic,assign) NSInteger indexOfDetailType;//当前默认选中的请假具体原因
@property (nonatomic, strong) NSMutableArray *classeids;
@property (nonatomic, strong) NSMutableArray *classes;

@property (nonatomic, strong) DropDownMenu2 *dropList;

//@property (nonatomic,strong)  UIControl *control;
@end

@implementation SYHomeParLeaveViewController{
    
    NSString *classID;
    NSMutableArray *qingJiaListArr;
    NSString *leaveTypeStr;
    
    
    NSString *typeID;
    NSString *childID;
    UIControl *control;
    
    NSMutableArray * stuAndClassArray;
    
    NSString * stuId;
    NSString * className;
    NSString * stuName;
    NSString *classId;
    
    int selTypeFlag;
}

//-(UIControl *)control
//{
//    if (_control==nil) {
//        
//        _control=[[UIControl alloc]initWithFrame:CGRectMake(0, SCREENHEIGH-200, SCREENWIDTH, 200)];
//        _control.backgroundColor=[UIColor whiteColor];
//        UIButton *sureBtn=[UIButton buttonWithType:UIButtonTypeCustom];
//        sureBtn.frame=CGRectMake(SCREENWIDTH-12-40, 0, 40, 30);
//        [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
//        [sureBtn setTitleColor:RGBACOLOR(57, 173, 255, 1) forState:UIControlStateNormal];
//        [sureBtn addTarget:self action:@selector(chooseType:) forControlEvents:UIControlEventTouchUpInside];
//        
//        [_control addSubview:sureBtn];
//        [_control addSubview:self.picker];
//        [self.view addSubview:_control];
//    }
//    return _control;
//}
#pragma mark -getter

-(void)getDateViewStart{
    
        __weak typeof(self) weakSelf = self;
    
       [_dateViewStart removeFromSuperview];
        _dateViewStart = [[DateView alloc] initAddSuperView:self.view canceltype:2];
    
        _dateViewStart.getDate = ^(NSString *dateStr){
            NSMutableString * dateS = [NSMutableString stringWithFormat:@"%@",dateStr];
            NSString * date = [[dateS componentsSeparatedByString:@" "] firstObject];
            weakSelf.selStartDate.textField.text = date;
            [weakSelf getLeaveDays:weakSelf.selEndDate.textField.text andStart:date andFlag:0];

        };
}



-(void)getDateViewStop{
    
    __weak typeof(self) weakSelf = self;

       [_dateViewStop removeFromSuperview];

        _dateViewStop = [[DateView alloc] initAddSuperView:self.view canceltype:2];
        _dateViewStop.getDate = ^(NSString *dateStr){
            NSMutableString * dateS = [NSMutableString stringWithFormat:@"%@",dateStr];
            NSString * date = [[dateS componentsSeparatedByString:@" "] firstObject];
            weakSelf.selEndDate.textField.text = date;
            [weakSelf getLeaveDays:date andStart:weakSelf.selStartDate.textField.text andFlag:1];
        };

}


- (void)getLeaveDays:(NSString *)endString andStart:(NSString *)startString andFlag:(int)flag
{
    if (flag==0) {
        
        if (endString.length>0) {
            
            NSUInteger endtime = [Utils transformStringToNsinterger:endString];
            NSUInteger startTim = [Utils transformStringToNsinterger:startString];
            
            if (endtime<startTim) {
                [Utils alertViewWithMessage:@"结束时间应该大于或等于开始时间"];
                return;
            }else if (endtime==startTim)
            {
                _selDays.textField.text=@"1";
            }else
            {
                NSDateFormatter *format=[[NSDateFormatter alloc] init];
                [format setDateFormat:@"yyyy-MM-dd"];
                NSTimeInterval time=[[format dateFromString:endString] timeIntervalSinceDate:[format dateFromString:startString] ];
                int days=((int)time)/(3600*24)+1;
                _selDays.textField.text=[NSString stringWithFormat:@"%d",days];
            }
        }
    }
    
    if (flag==1) {
        
        if (startString.length>0) {
            
            NSUInteger endtime = [Utils transformStringToNsinterger:endString];
            NSUInteger startTim = [Utils transformStringToNsinterger:startString];
            
            if (endtime<startTim) {
                [Utils alertViewWithMessage:@"结束时间应该大于或等于开始时间"];
                return;
            }else if (endtime==startTim)
            {
                _selDays.textField.text=@"1";
            }else
            {
                NSDateFormatter *format=[[NSDateFormatter alloc] init];
                [format setDateFormat:@"yyyy-MM-dd"];
                NSTimeInterval time=[[format dateFromString:endString] timeIntervalSinceDate:[format dateFromString:startString] ];
                int days=((int)time)/(3600*24)+1;
                _selDays.textField.text=[NSString stringWithFormat:@"%d",days];
            }
        }else
        {
            [Utils alertViewWithMessage:@"请选择开始时间"];
            return;
        }

    }
    
}
//隐藏键盘的点击手势
-(UITapGestureRecognizer *)keyBoardHideTap{
    
    if (!_keyBoardHideTap) {
        
        _keyBoardHideTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapToResignKeyboardAction:)];
        
    }
    
    return _keyBoardHideTap;
}

-(UIPickerView *)picker{
    
    if (!_picker) {
        
        _picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, SCREENHEIGH-170, SCREENWIDTH, 170)];
        _picker.delegate = self;
        _picker.dataSource = self;
        _picker.showsSelectionIndicator = NO;
        _picker.backgroundColor=[UIColor whiteColor];
        _picker.userInteractionEnabled=YES;
        
    }
    
    return _picker;
}


-(UIPickerView *)classPicker{
    
    if (!_classPicker) {
        
        _classPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, SCREENHEIGH-170, SCREENWIDTH, 170)];
        _classPicker.delegate = self;
        _classPicker.dataSource = self;
        _classPicker.showsSelectionIndicator = NO;
        _classPicker.backgroundColor=[UIColor whiteColor];
        _classPicker.userInteractionEnabled=YES;
        
    }
    
    return _classPicker;
}

-(void)tapToResignKeyboardAction:(UIGestureRecognizer *)gezr{
    
    [self.view endEditing:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _classeids=[NSMutableArray array];
    _classes=[NSMutableArray array];
    
    [self DownStuAndClassList];
    //获取请假类型
    [self DownLeaveTypeList];
    
//    [self allClassData];
    
    self.navBar.nav_titleLabel.text = @"请假";
    self.view.backgroundColor = TABLEHEADERBGCOLOR;
    
    [self configureUI];
    
    [self keyBtn];
    
    [self.view addGestureRecognizer:self.keyBoardHideTap];
    
    //监听键盘
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardWillHideNotification object:nil];
    

}

-(void)allClassData{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    [param setObject:@"api_classone_search" forKey:@"method"];
    if (USERID) {
        
        [param setObject:USERID forKey:@"userid"];
    }
    [param setObject:@"1" forKey:@"pageno"];
    [param setObject:@"1000000000" forKey:@"pagesize"];
    [param setObject:@"1" forKey:@"state"];
    [param setObject:@"2"forKey:@"type"];
    
    [Utils getAllClass:nil parameters:param success:^(NSInteger recode, id jsonObject) {
        
        NSArray *arr = [jsonObject objectForKey:@"re_data"];
        
        if (arr.count == 0) {  //没有班级
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message: @"请先加入班级" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
            
            alert.tag = 101;
            [alert show];
            
        }else if(arr.count > 0){
            
            [self->_classeids addObjectsFromArray:arr];
            
            for (NSDictionary *dic in arr) {
                
                NSString *className1 = [dic objectForKey:@"classename"];
                
                [self->_classes addObject:className1];
            }
        }
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
    
}

-(void)DownStuAndClassList
{
    
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:USERID forKey:@"parentid"];
   
    [Utils Java_get:@"api/getChildClass" parameters:dict success:^(NSInteger recode, id jsonObject) {
      
       NSArray *array=[jsonObject objectForKey:@"re_data"];
       
      self->stuAndClassArray =[NSMutableArray arrayWithArray:array];
       
    } failure:^(NSInteger recode, NSError *error) {
      
    }];
   
   
   
//    [Utils get:nil parameters:dict success:^(NSInteger recode, id jsonObject){
//        NSDictionary *dict = (NSDictionary *)jsonObject;
//
//        NSArray *array=[dict objectForKey:@"re_data"];
//        self->stuAndClassArray =[NSMutableArray arrayWithArray:array];
//
//
//    } failure:^(NSInteger recode, NSError *error) {
//
//    }];
   

}

//请求请假类型列表
-(void)DownLeaveTypeList
{
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"api_leave_typelist" forKey:@"method"];
    [dict setObject:@"1" forKey:@"parentid"];
    [Utils get:nil parameters:dict success:^(NSInteger recode, id jsonObject){
        NSDictionary *dict = (NSDictionary *)jsonObject;
        
        NSArray *array=[dict objectForKey:@"re_data"];
        
        self->qingJiaListArr=[NSMutableArray arrayWithArray:array];
        
        
        NSArray *sjArr=@[@{@"typeid":@"2",@"typename":@"事假"}];
        NSArray *otherArr=@[@{@"typeid":@"15",@"typename":@"其它"}];
        
        NSMutableDictionary *sjDic=[NSMutableDictionary dictionaryWithDictionary:[self->qingJiaListArr objectAtIndex:1]];
        [sjDic setObject:sjArr forKey:@"item"];
        [self->qingJiaListArr replaceObjectAtIndex:1 withObject:sjDic];
        
        NSMutableDictionary *otherDic=[NSMutableDictionary dictionaryWithDictionary:[self->qingJiaListArr objectAtIndex:2]];
        [otherDic setObject:otherArr forKey:@"item"];
        [self->qingJiaListArr replaceObjectAtIndex:2 withObject:otherDic];
        
        
    } failure:^(NSInteger recode, NSError *error){
        
    }];
    
    
}

-(void)configureUI{
    
    CGFloat y;
    
    _selClass = [[SYLeaveSelView alloc] initWithFrame:CGRectMake(0, 14+SafeAreaTopHeight, VIEW_WIDTH, 40)];
    _selClass.delegate = self;
    _selClass.leftLabel.text = @"请假宝宝";
    _selClass.textField.tag = 1;
    [self.view addSubview:_selClass];
    
    y = CGRectGetMaxY(_selClass.frame) + 10;
    
    _selType = [[SYLeaveSelView alloc] initWithFrame:CGRectMake(0, y, VIEW_WIDTH, 40)];
    _selType.delegate = self;
    _selType.leftLabel.text = @"请假类型";
    _selType.leftLabel.tintColor = [UIColor clearColor];
    _selType.textField.tag = 2;
//    _selType.textField.inputView = self.picker;
    [self.view addSubview:_selType];
    
    y = CGRectGetMaxY(_selType.frame) + 10;
    _selStartDate = [[SYLeaveSelView alloc] initWithFrame:CGRectMake(0, y, VIEW_WIDTH, 40)];
    _selStartDate.delegate = self;
    _selStartDate.leftLabel.text = @"开始时间";
    _selStartDate.leftLabel.tintColor = [UIColor clearColor];
    _selStartDate.textField.tag = 3;
//    _selStartDate.textField.inputView = self.dateViewStart;
    [self.view addSubview:_selStartDate];
    
    y = CGRectGetMaxY(_selStartDate.frame);
    _selEndDate = [[SYLeaveSelView alloc] initWithFrame:CGRectMake(0, y, VIEW_WIDTH, 40)];
    _selEndDate.delegate = self;
    _selEndDate.topLineView.hidden = YES;
    _selEndDate.leftLabel.text = @"结束时间";
    _selEndDate.leftLabel.tintColor = [UIColor clearColor];
//    _selEndDate.textField.inputView = self.dateViewStop;
    _selEndDate.textField.tag = 4;
    [self.view addSubview:_selEndDate];
    
    y = CGRectGetMaxY(_selEndDate.frame) + 10;
    _selDays = [[SYLeaveSelView alloc] initWithFrame:CGRectMake(0, y, VIEW_WIDTH, 40)];
    _selDays.delegate = self;
    _selDays.leftLabel.text = @"请假天数";
    _selDays.textField.tag = 5;
    _selDays.textField.keyboardType=UIKeyboardTypeNumberPad;
    _selDays.textField.frame = CGRectMake(100, 0, 300, 40);
    _selDays.textField.placeholder = @"请输入请假天数";
    _selDays.textField.textAlignment=NSTextAlignmentLeft;
    [self.view addSubview:_selDays];
    
    y = CGRectGetMaxY(_selDays.frame) + 10;
    _contentView = [[UIView alloc] initWithFrame:CGRectMake(0, y, VIEW_WIDTH, 130)];
    _contentView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_contentView];
    
    UILabel *leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(12, 14, 80, 15)];
    leftLabel.font = [UIFont systemFontOfSize:15];
    leftLabel.textColor = RGBCOLOR(59, 59, 59);
    leftLabel.text = @"请假事由";
    [_contentView addSubview:leftLabel];
    

    _inputView = [[XHMessageTextView alloc] initWithFrame:CGRectMake(90, 4, VIEW_WIDTH - 90, 110)];
    _inputView.placeHolder = @"请输入请假事由";
    _inputView.delegate = self;
    [_contentView addSubview:_inputView];
    
    _countLabel = [[UILabel alloc] initWithFrame:CGRectMake(VIEW_WIDTH - 100 - 12, CGRectGetMaxY(_inputView.frame), 100, 10)];
    _countLabel.textAlignment = NSTextAlignmentRight;
    _countLabel.textColor = RGBCOLOR(199, 199, 204);
    _countLabel.font = [UIFont systemFontOfSize:10];
    _countLabel.text = @"0/100";
    [_contentView addSubview:_countLabel];
    
    UIButton *submitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    submitBtn.frame = CGRectMake(12, SCREENHEIGH - 86-64+64, VIEW_WIDTH - 24, 36);
    [submitBtn setTitle:@"提交" forState:UIControlStateNormal];
    [submitBtn setBackgroundColor:RGBCOLOR(0, 180, 255)];
    submitBtn.layer.cornerRadius = 6;
    [submitBtn addTarget:self action:@selector(submintAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:submitBtn];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(BOOL)selActionWithSender:(UITextField *)selBtn{
    
    if (selBtn.tag == 1) {
        
        [self.selDays.textField resignFirstResponder];
        [self.inputView resignFirstResponder];
        [control removeFromSuperview];
        
        [self loadLeaveTypeView:1];
        
        return NO;
    }
    
    if (selBtn.tag == 2) {
        
        [self.selDays.textField resignFirstResponder];
        [self.inputView resignFirstResponder];
        [self loadLeaveTypeView:2];
        
        return NO;
    }
    
    if (selBtn.tag == 3) {
    
        [self.selDays.textField resignFirstResponder];
        [self.inputView resignFirstResponder];
        [control removeFromSuperview];
        

        [self getDateViewStart];

        
        return NO;
    }
    
    if (selBtn.tag == 4) {
        
        [self.selDays.textField resignFirstResponder];
        [self.inputView resignFirstResponder];
        [control removeFromSuperview];

        [self getDateViewStop];

        
        return NO;
    }
    
    if (selBtn.tag == 5) {
        [control removeFromSuperview];
    }
    
    return YES;
}

- (void)setupMenuWithArray:(NSArray *)array
{
    
    NSMutableArray * celltitles = [[NSMutableArray alloc] initWithCapacity:0];
    for (NSDictionary *classDict in array) {
        NSString *className1 = [classDict objectForKey:@"classname"];
        [celltitles addObject:className1];
    }
    [self.dropList setDropDownMenuParameterWithcellContents:celltitles andWidth:125];
}
- (void) niDropDownDelegateMethod:(DropDownMenu2 *) sender{
    
    NSDictionary *classdic=[_classeids objectAtIndex:sender.senderTag];
    _selClass.textField.text=[classdic objectForKey:@"classname"];
    self->classID=[classdic objectForKey:@"classid"];
    
}


#pragma mark -UITextViewDelegate
-(void)textViewDidChange:(UITextView *)textView{
    
    NSInteger length = textView.text.length;
    
    NSString *oriStr = [NSString stringWithFormat:@"%d/100",(int)length];
    
    NSRange range = [oriStr rangeOfString:@"/"];
    
    
    if (textView.text.length > 100) {
        UITextRange *markedRange = [textView markedTextRange];
        if (markedRange) {
            return;
        }
        //Emoji占2个字符，如果是超出了半个Emoji，用15位置来截取会出现Emoji截为2半
        //超出最大长度的那个字符序列(Emoji算一个字符序列)的range
        NSRange range = [textView.text rangeOfComposedCharacterSequenceAtIndex:100];
        textView.text = [textView.text substringToIndex:range.location];
    }
    
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:oriStr];
    
    if (length > 90) {
        
        [attributeStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, range.location)];
    }
    
    _countLabel.attributedText = attributeStr;
    
}

#pragma mark -提交
-(void)submintAction:(UIButton *)sender{
    
//    NSUserDefaults *ud=[NSUserDefaults standardUserDefaults];
//    NSString *studentID=[ud objectForKey:@"studentID"];
//    if (studentID!=nil) {
//        
//        childID=studentID;
//        
//    }else
//    {
//        [Utils alertViewWithMessage:@"请先关联学生"];
//    }
    NSUInteger endtime = [Utils transformStringToNsinterger:_selEndDate.textField.text];
    NSUInteger startTim = [Utils transformStringToNsinterger:_selStartDate.textField.text];
    if (_selClass.textField.text.length==0) {
        
        [Utils alertViewWithMessage:@"请选择宝宝"];
        return;
    }
    if (_selType.textField.text.length==0) {
        
        [Utils alertViewWithMessage:@"请选择请假类型"];
        return;
    }
    if (_selStartDate.textField.text.length==0) {
        
        [Utils alertViewWithMessage:@"请选择开始时间"];
        return;
    }
    if (_selStartDate.textField.text.length==0) {
        
        [Utils alertViewWithMessage:@"请选择结束时间"];
        return;
    }
    
    if (startTim>endtime) {
        [Utils alertViewWithMessage:@"结束时间应该大于或等于开始时间"];
        return;
    }
    if (_selDays.textField.text.length==0) {
        
        [Utils alertViewWithMessage:@"请填写请假天数"];
        return;
    }
    
    if ([[_inputView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0)
    {
        [Utils alertViewWithMessage:@"请填写请假事由"];
        return;
    }
    if (_inputView.text.length>100) {
        [Utils alertViewWithMessage:@"请填写请假事由限制在100字以内"];
        return;
    }
    BOOL contentcontains = [Utils stringContainsEmoji:_inputView.text];
    if (contentcontains) {
        [Utils alertViewWithMessage:@"请假事由不能含有特殊字符"];
        return;
    }
    
    BaseModel *param = [BaseModel param];
    param.method = @"api_leave_add";
    param.classid= classID;
    param.starttime= _selStartDate.textField.text;
    param.endtime= _selEndDate.textField.text;
    param.flong = _selDays.textField.text;
    param.parentid = USERID;
    param.scontent = _inputView.text;
    param.type = typeID;
    param.studentid = stuId;

    
    [Utils get:nil parameters:param.mj_keyValues success:^(NSInteger recode, id jsonObject) {
        
        NSString *message=[jsonObject objectForKey:@"re_info"];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"requestLeaveData" object:nil];
        [self.navigationController popViewControllerAnimated:YES];
        
        
    } failure:^(NSInteger recode, NSError *error) {
        
        [self showHint:@"网络异常,请稍后重试!"];
    }];

}

#pragma mark -UIPickerViewDataSource && UIPickerViewDelegate
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    
    return 2;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    
    if (component == 0) {
        
        if (pickerView == self.picker) {
            
            return qingJiaListArr.count;
        }else
        {
            return stuAndClassArray.count;
        }
        
    }
    
    if (pickerView == self.picker) {
        
      //获取对应省份的城市个数
       NSArray *array = [qingJiaListArr[self.indexOfType] objectForKey:@"item"];
    
       return array.count;
        
    }else
    {
        NSArray *array = [[stuAndClassArray objectAtIndex:self.indexOfType] objectForKey:@"item"];
        
        return array.count;
    }
    
}

#pragma mark 显示数据
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if(component == 0){//显示省份的名字
        
         if (pickerView == self.picker) {
        //对应列行的省份
            NSString *name=[[qingJiaListArr objectAtIndex:row] objectForKey:@"typename"];
            return name;
         }else
         {
             NSString *stuName1=[[stuAndClassArray objectAtIndex:row] objectForKey:@"studentname"];
             return stuName1;
         }
    }
    
    
     if (pickerView == self.picker) {
       //获取选中的城市，显示城市名字
        NSArray *arr = [[qingJiaListArr objectAtIndex:_indexOfType] objectForKey:@"item"];
        NSString *typeName=[[arr objectAtIndex:row] objectForKey:@"typename"];
        return typeName;
         
     }else
     {
         NSArray *arr = [[stuAndClassArray objectAtIndex:_indexOfType] objectForKey:@"item"];
         NSString *className1=[[arr objectAtIndex:row] objectForKey:@"classname"];
         return className1;
     }

}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    
    UILabel* pickerLabel = (UILabel*)view;
    
    if (!pickerLabel){
        
        pickerLabel = [[UILabel alloc] init];
        
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        
        [pickerLabel setFont:[UIFont boldSystemFontOfSize:15]];
        
    }

    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    
    return pickerLabel;
    
}

#pragma mark 选中行

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    if (component == 0) {//第一列省的选中改变后，就要更新第二列数据
        //更新选中省份的索引
        self.indexOfType = row;
        
        //刷新数据
        //全部刷新
        //[pickerView reloadAllComponents];
        
        //部份刷新
        [pickerView reloadComponent:1];
        
        //不管之前第二列选中第几行，重新刷新数据后，都显示每二列的第一行
        [pickerView selectRow:0 inComponent:1 animated:YES];
        self.indexOfDetailType = 0;
    }else
    {
        self.indexOfDetailType = row;
    }
    
}

#pragma mark 设置宽度
-(CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
    if (component == 0) {
        return 80;
    }
    
    return 200;
}

#pragma mark -键盘显示与隐藏的监听事件
-(void)keyboardDidShow:(NSNotification *)noti{
    
    if ([_inputView isFirstResponder]) {
        
        
        CGFloat maxY = CGRectGetMaxY(self.contentView.frame);
        
        NSDictionary *dict = noti.userInfo;
        CGRect rect =  [[dict objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
        CGFloat keyboardY = rect.origin.y;
        
        if (maxY > keyboardY) { //需要移动
            
            CGRect viewRect = self.view.frame;
            viewRect.origin.y =  keyboardY - maxY;
            self.view.frame = viewRect;
        }
        
    }
    
}

-(void)keyboardDidHide:(NSNotification *)noti{
    
    CGRect viewRect = self.view.frame;
    
    viewRect.origin.y = 0;
    self.view.frame = viewRect;
}

- (void)loadLeaveTypeView:(int)flag
{

    [control removeFromSuperview];
    control=[[UIControl alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGH)];
    control.backgroundColor=[UIColor clearColor];
    [control addTarget:self action:@selector(cancelControlAction) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *sureBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    sureBtn.frame=CGRectMake(SCREENWIDTH-12-40,SCREENHEIGH-200, 40, 30);
    [sureBtn setTitle:@"完成" forState:UIControlStateNormal];
    [sureBtn setTitleColor:RGBACOLOR(57, 173, 255, 1) forState:UIControlStateNormal];
    [sureBtn addTarget:self action:@selector(chooseTypeAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [control addSubview:sureBtn];
    
    if (selTypeFlag != flag) {  //这次选的和上一次不一样
        
        self.indexOfType = 0;
        self.indexOfDetailType = 0;
        
        self.classPicker = nil;
        self.picker = nil;
    }
    
    if (flag == 1) {
        
        [control addSubview:self.classPicker];
        sureBtn.tag = 1;
    }else
    {
        
        [control addSubview:self.picker];
        sureBtn.tag = 2;
    }
    
    selTypeFlag = flag;
    
    UIWindow *window = KeyWindow;
    [window addSubview:control];

    
}


- (void)cancelControlAction
{
    [control removeFromSuperview];
}
- (void) chooseTypeAction:(UIButton *)sender
{
    [control removeFromSuperview];
    
    if (sender.tag == 1) {
        
        NSDictionary  *typeDic=[stuAndClassArray objectAtIndex:_indexOfType];
        
        stuName = [typeDic objectForKey:@"studentname"];
        stuId = [typeDic objectForKey:@"studentid"];
        
        
        NSArray *arr=[typeDic objectForKey:@"item"];

        if (arr.count>0) {
            className=[[arr objectAtIndex:_indexOfDetailType] objectForKey:@"classname"];
            classID=[[arr objectAtIndex:_indexOfDetailType] objectForKey:@"classid"];
        }
        
        _selClass.textField.text = [NSString stringWithFormat:@"%@ %@",stuName,className] ;
        
    }else
    {
    
        NSDictionary  *typeDic=[qingJiaListArr objectAtIndex:_indexOfType];
        
        NSArray *arr=[typeDic objectForKey:@"item"];
        
        if (arr.count>0) {
            leaveTypeStr=[[arr objectAtIndex:_indexOfDetailType] objectForKey:@"typename"];
            typeID=[[arr objectAtIndex:_indexOfDetailType] objectForKey:@"typeid"];
        }else
        {
            leaveTypeStr=[typeDic objectForKey:@"typename"];
            typeID=[typeDic objectForKey:@"typeid"];
        }
        
        _selType.textField.text = leaveTypeStr;
    }
    
}
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    
    return NO;
    
}
-(void)keyBtn
{
    UIToolbar * topView = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 40)];
    [topView setBarStyle:UIBarStyleDefault];
    topView.backgroundColor=[UIColor whiteColor];
    UIBarButtonItem * btnSpace = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    
    UIBarButtonItem * doneBtn = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(dismissKeyBoard)];
    NSArray * buttonsArray = [NSArray arrayWithObjects:btnSpace,doneBtn,nil];
    [topView setItems:buttonsArray];
    
    [_inputView setInputAccessoryView:topView];
}
-(void)dismissKeyBoard
{
    [_inputView resignFirstResponder];
}
-(void)textViewDidBeginEditing:(UITextView *)textView
{
    [control removeFromSuperview];
}

@end
